﻿using yao.Common;
using yao.Entity;
using yao.Mvc;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 期初库存
    /// </summary>
    public class StoreInitialController : BaseController
    {
        public ActionResult Index(long id)
        {
            using (IDbSession cn = OpenSession())
            {
                Product product = new Product { ProductId = id };
                cn.Select(product,Product_.ProductName,Product_.ProductNo);

                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(StoreInitial);
                q.Selects.Add(StoreInitial_.ProductId);
                q.Selects.Add(StoreInitial_.QualityStyleId);
                q.Selects.Add(StoreInitial_.LotNo);
                q.Selects.Add(StoreInitial_.StoreId);
                q.Selects.Add(StoreInitial_.Store.StoreName);
                q.Selects.Add(StoreInitial_.Quantity);
                q.Selects.Add(StoreInitial_.Store.StoreName);
                q.Wheres.Add(StoreInitial_.ProductId.TEqual(id));
                q.ReturnMatchedCount = true;
                StoreInitials storeInitials = new StoreInitials();
                cn.SelectCollection(storeInitials.Items, q);

                ViewData["StoreInitials"] = storeInitials;
                return View(product);
            }
        }

        [HttpPost]
        public ActionResult Index(Product product)
        {
            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    long productId = 0;
                    long.TryParse(Request.Form["ProductId"], out productId);//商品ID
                    if (productId < 0) {
                        AddPageError("商品ID不能为空");
                        return View(product);
                    }

                    int storeInitialLineRow = 0;
                    if (!int.TryParse(Request.Form["StoreInitialLineRow"], out storeInitialLineRow))
                    {
                        AddPageError("数据提交有误");
                        return View(product);
                    }

                    #region 获取当前提交的数据
                    Dictionary<string, StoreInitial> dicStoreInitial = new Dictionary<string, StoreInitial>();
                    for (var i = 0; i < storeInitialLineRow; i++)
                    {
                        decimal Quantity;
                        decimal.TryParse(Request.Form["Quantity_" + i], out Quantity);//数量

                        string LotNo = Request.Form["LotNo_" + i];//批号

                        long StoreId;
                        long.TryParse(Request.Form["StoreId_" + i], out StoreId);//仓库

                        if (string.IsNullOrEmpty(LotNo) || StoreId <= 0 || Quantity <= 0)
                        {
                            continue;
                        }
                        StoreInitial storeInitial = new StoreInitial
                        {
                            ProductId = productId,
                            Quantity = Quantity,
                            LotNo = LotNo,
                            StoreId=StoreId,
                            QualityStyleId = QualityStyle.Qualified
                        };

                        string key = string.Format("{0}_{1}_{2}_{3}", storeInitial.ProductId, storeInitial.LotNo, storeInitial.QualityStyleId, storeInitial.StoreId);
                        if (dicStoreInitial.ContainsKey(key))
                        {
                            dicStoreInitial[key].Quantity += storeInitial.Quantity;
                        }
                        else
                        {
                            dicStoreInitial.Add(key, storeInitial);
                        }
                    }
                    #endregion

                    if (dicStoreInitial.Count <= 0) {
                        AddPageError("数据提交有误");
                        return View(product);
                    }

                    #region 根据productId 读取数据库 做数据对比
                    QueryExpression q = new QueryExpression();
                    q.EntityType = typeof(StoreInitial);
                    q.Selects.Add(StoreInitial_.ProductId);
                    q.Selects.Add(StoreInitial_.QualityStyleId);
                    q.Selects.Add(StoreInitial_.LotNo);
                    q.Selects.Add(StoreInitial_.StoreId);
                    q.Selects.Add(StoreInitial_.Quantity);
                    q.Selects.Add(StoreInitial_.Store.StoreName);
                    q.Wheres.Add(StoreInitial_.ProductId.TEqual(productId));
                    StoreInitials storeInitialsFromDB = new StoreInitials();
                    cn.SelectCollection(storeInitialsFromDB.Items, q);
                    #endregion

                    //第一次进行添加
                    if (storeInitialsFromDB.Items.Count <= 0)
                    {
                        foreach (KeyValuePair<string,StoreInitial> key in dicStoreInitial)
                        {
                            StoreInitial storeInitial = key.Value;
                            cn.Insert(storeInitial);
                            UpdateProduct(cn, storeInitial.Quantity, storeInitial.ProductId);
                            UpdateStoreProduct(cn, storeInitial.Quantity, storeInitial.ProductId, storeInitial.LotNo, storeInitial.StoreId);
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair<string, StoreInitial> key in dicStoreInitial)
                        {
                            StoreInitial storeInitial = key.Value;

                            #region 一个都没改变
                            if (storeInitialsFromDB.Items.Where(p => p.StoreId.Equals(storeInitial.StoreId) && p.LotNo.Equals(storeInitial.LotNo) && p.Quantity.Equals(storeInitial.Quantity)).Count() > 0)
                            {
                                continue;
                            }
                            #endregion

                            //Quantity 变化(主键没变化)
                            var change1 = storeInitialsFromDB.Items.Where(p => p.StoreId.Equals(storeInitial.StoreId) && p.LotNo.Equals(storeInitial.LotNo) && p.QualityStyleId.Equals(storeInitial.QualityStyleId) && !p.Quantity.Equals(storeInitial.Quantity));
                            if (change1.Count() > 0)
                            {
                                decimal diff = storeInitial.Quantity - change1.First().Quantity;
                                UpdateProduct(cn, diff, storeInitial.ProductId);
                                UpdateStoreProduct(cn, diff, storeInitial.ProductId, storeInitial.LotNo, storeInitial.StoreId);
                                cn.Update(storeInitial, StoreInitial_.Quantity);
                            }
                            else
                            {
                                //主键变化了
                                cn.Insert(storeInitial);
                                UpdateProduct(cn, storeInitial.Quantity, productId);
                                UpdateStoreProduct(cn, storeInitial.Quantity,storeInitial.ProductId,storeInitial.LotNo,storeInitial.StoreId);
                            }
                        }

                        #region 数据库记录没有这条记录，就进行添加
                        foreach (StoreInitial storeInitial in storeInitialsFromDB.Items)
                        {
                            if (dicStoreInitial.Where(p => p.Value.StoreId.Equals(storeInitial.StoreId) && p.Value.LotNo.Equals(storeInitial.LotNo) && p.Value.QualityStyleId.Equals(storeInitial.QualityStyleId)).Count() < 0) {
                                cn.Delete(storeInitial);
                                UpdateProduct(cn, -storeInitial.Quantity, storeInitial.ProductId);
                                UpdateStoreProduct(cn, -storeInitial.Quantity, storeInitial.ProductId, storeInitial.LotNo, storeInitial.StoreId);
                            }
                        }
                        #endregion
                    }

                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }

            return new IframeResult(Url.Action("Index", "StoreInitial"), Url.Action("Index", "Product"));
        }


        private void UpdateProduct(IDbSession cn, decimal quantity, long productId)
        {
            MySqlCommand cmdProduct = new MySqlCommand("update Product set UseableCount=UseableCount+@UseableCount,StoreCount=StoreCount+@StoreCount where ProductId=@ProductId");
            cmdProduct.Parameters.AddWithValue("@UseableCount", quantity);
            cmdProduct.Parameters.AddWithValue("@StoreCount", quantity);
            cmdProduct.Parameters.AddWithValue("@ProductId", productId);
            cn.ExecuteNonQuery(cmdProduct);
        }
        private void UpdateStoreProduct(IDbSession cn, decimal quantity, long productId, string lotNo, long storeId)
        {
            StoreProduct storeProduct = new StoreProduct
            {
                ProductId = productId,
                LockQuantity = 0,
                LotNo = lotNo,
                QualityStyleId = QualityStyle.Qualified,
                Quantity = quantity,
                StoreId = storeId,
                UseableQuantity = quantity
            };
            if (cn.Exists(storeProduct))
            {
                MySqlCommand cmdStoreProduct = new MySqlCommand("update StoreProduct set UseableQuantity=UseableQuantity+@UseableQuantity,Quantity=Quantity+@Quantity where ProductId=@ProductId and LotNo=@LotNo and StoreId=@StoreId and QualityStyleId=1");
                cmdStoreProduct.Parameters.AddWithValue("@UseableQuantity", quantity);
                cmdStoreProduct.Parameters.AddWithValue("@Quantity", quantity);
                cmdStoreProduct.Parameters.AddWithValue("@ProductId", productId);
                cmdStoreProduct.Parameters.AddWithValue("@LotNo", lotNo);
                cmdStoreProduct.Parameters.AddWithValue("@StoreId", storeId);
                cn.ExecuteNonQuery(cmdStoreProduct);
            }
            else {
                cn.Insert(storeProduct);
            }
        }

        /// <summary>
        /// 删除库存表数据（当总数为0的时候）
        /// </summary>
        /// <param name="cn"></param>
        /// <param name="productId"></param>
        /// <param name="lotNo"></param>
        /// <param name="storeId"></param>
        private void DeleteStoreProduct(IDbSession cn,long productId, string lotNo, long storeId)
        {
            StoreProduct storeProduct = new StoreProduct
            {
                ProductId = productId,
                StoreId = storeId,
                LotNo = lotNo,
                QualityStyleId = QualityStyle.Qualified
            };
            cn.Delete(storeProduct);
        }
    }
}                                                                               
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                